package crm.controller;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.sql.SQLIntegrityConstraintViolationException;

import javax.swing.JOptionPane;

import org.apache.derby.impl.sql.compile.LengthOperatorNode;

import crm.daoInterfaces.CampaignDao;
import crm.implementor.CampaignImp;
import crm.model.Campaign;
import crm.utility.AppUtility;
import crm.utility.Browser;
import crm.utility.ViewUtilites;
import crm.view.campaign.CampaignManagment;
import crm.viewframework.Validater;



public class CampaignMgmtController extends Browser implements ActionListener {
	private CampaignManagment view;
	private Campaign model;
	private Campaign[]campaigns;
	
	
	
/*****************************************CONSTRUCTORS*************************************************************/
	public CampaignMgmtController() {
	
	}

	public CampaignMgmtController(CampaignManagment view, Campaign model) {
		super();
		this.view = view;
		this.model = model;
		view.actionListener(this);
		CampaignDao cd=new CampaignImp();
		try {
			campaigns=cd.retrieveAll();
			maxLength=campaigns.length;
			this.setLabelVisibility(false);
			AppUtility.setComboAtten(view.getComboCreatedBy());
			
			
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		index=-1;
		
	}

/**********************************************GETTER AND SETTER*************************************************************/	
	public CampaignManagment getView() {
		return view;
	}

	public void setView(CampaignManagment view) {
		this.view = view;
	}

	public Campaign getModel() {
		return model;
	}

	public void setModel(Campaign model) {
		this.model = model;
	}

/**********************************************STATIC PART*************************************************************/	
	
	private void reactOnSave()
	{
		String campName=view.gettCampName().getText();
		String createdBy=view.getComboCreatedBy().getSelectedItem().toString();
		Date startDate;
		Date endDate;
		try {
			startDate = ViewUtilites.convert(view.gettStartDate().getText());
			endDate=ViewUtilites.convert(view.gettEndDate().getText());
		} catch (Exception e1) {
			
			JOptionPane.showMessageDialog(null,"Please Select The Date");
			e1.printStackTrace();
			return;
			
		}
		String descrip=view.getTextAreaDescription().getText();
		model=new Campaign(0, campName, startDate, endDate, descrip, createdBy, 1);
		CampaignDao cd=new CampaignImp();
		try
		{
			cd.add(model);
			campaigns=cd.retrieveAll();  // refresh the campaign array
			index=0;
			JOptionPane.showMessageDialog(null, "Data successfully added");
		}
	
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
			e.printStackTrace();
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
			e.printStackTrace();
		
		}
		
		
	}
	
	private void reactOnMarkInactive() throws Exception
	{
		String campname=view.gettCampName().getText();
		CampaignDao campdao=new CampaignImp();
		Campaign c=null;
		try
		{
			c=campdao.retrieve("campaignName", campname);
			if(c.getStatus()==1)
				c.setStatus(0);
			else
				c.setStatus(1);
		}
		catch(Exception e)
		{
			
			e.printStackTrace();
		}
		
		
		campdao.update(c);
	}
	
	private void reactOnUpdate() throws Exception
	{
		String campname=view.gettCampName().getText();
		
		CampaignDao cd=new CampaignImp();
		model=cd.retrieve( "campaignName", campname);
		
		Date endDate=ViewUtilites.convert(view.gettEndDate().getText());
		Date startDate=ViewUtilites.convert(view.gettStartDate().getText());
		model.setCampaignStartDate(startDate);
		model.setCampaignEndDate(endDate);
		String createdBy=view.gettCampName().getText();
		
		model.setCreatedBy(createdBy);
		
		
		model.setDescription(view.getTextAreaDescription().getText());
		try
		{
			cd.update(model);
			JOptionPane.showMessageDialog(null, "Data successfully updated");
		}
	
		catch(SQLIntegrityConstraintViolationException e)
		{
			JOptionPane.showMessageDialog(null, "Name already exist, please use another one");
		}
		
		catch(Exception e)
		{
			JOptionPane.showMessageDialog(null, "Data not successfully added,Please try again !");
		
		}
		// The database is updated now , get all the sellers again
		 this.campaigns=cd.retrieveAll();
	}
	
	private void reactOnSearch() throws Exception
	{
		String campname=view.gettCampName().getText();
		CampaignDao cd=new CampaignImp();
		
		try
		{
		 model=null;
		 model=cd.retrieve( "campaignName", campname);
		 if(model==null)
		 {
			 JOptionPane.showMessageDialog(null," DATA NOT FOUND !");
			 refresh();
		 }
		}
		catch(Exception e)
		{
			
			e.printStackTrace();
		}
		if(model!=null)
		  fillViewFormFromModel();
		else
			JOptionPane.showMessageDialog(null, "Data Not Found !");
		// search has been done we need to update the index
		for(int i =0;i<campaigns.length;i++)
			{
			  if(campaigns[i].equals(campname))
			  {
				  index=i;
			  }
			}
			 
		
		
	}
	

	
	
	public void fillViewFormFromModel() throws Exception
	{
		model=this.campaigns[index];
		setLabelVisibility(true);
		view.gettCampName().setText(model.getCampaignName());
		AppUtility.setComboAtten(view.getComboCreatedBy());
		view.gettStartDate().setText(model.getCampaignStartDate()+"");
		view.gettEndDate().setText(model.getCampaignEndDate()+"");
		view.getTextAreaDescription().setText(model.getDescription());
		
		view.getLblCampaignId().setText(model.getAutocampaignId()+"");
		// Setting combo box;
		String[]data=new String[]{model.getCreatedBy()};
		ViewUtilites.set_comboBox(view.getComboCreatedBy(),data);
		
		if(model.getStatus()==1)
		{
			view.getBtnStatus().setText("MARK INACTIVE");
			view.getLblStatus().setText("ACTIVE");
		}
		
		if(model.getStatus()==0)
		{
			view.getBtnStatus().setText("MARK ACTIVE");
			view.getLblStatus().setText("INACTIVE");
			
		}
	}
	
	private void setLabelVisibility(boolean value)
	{
		view.getLabelCampaignId().setVisible(value);
		view.getLblCampaignId().setVisible(value);
		view.getLblCampaihnStatus().setVisible(value);
		view.getLblStatus().setVisible(value);
		view.getBtnStatus().setVisible(value);
	}
	
	private void refresh()
	{
		this.setLabelVisibility(false);
		Validater validater = new Validater(view);
		validater.refresh();
	}
	
	
/**********************************************DYNAMIC PART*************************************************************/	
	

	@Override
	public void actionPerformed(ActionEvent arg0) 
	{
		String k=arg0.getActionCommand();
		if(k.contains("SAVE"))
		{
			reactOnSave();
			JOptionPane.showMessageDialog(null,"SUCCSESS FULLY SAVED !");
			refresh();
		}
		if(k.contains("status"))
		{
			try {
				reactOnMarkInactive();
				JOptionPane.showMessageDialog(null,"SUCCSESS FULLY UPDATED !");
				refresh();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		if(k.contains("UPDATE"))
		{
			try {
				reactOnUpdate();
				JOptionPane.showMessageDialog(null,"SUCCSESS FULLY UPDATED !");
				refresh();
			
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		if(k.contains("<<"))
		{
			try {
				
				reactOnBack();
			} catch (Exception e) {
			
				e.printStackTrace();
			}
		}
		if(k.contains("SEARCH"))
		{
			try {
				reactOnSearch();
				
			} catch (Exception e) {
			
				e.printStackTrace();
			}
		}
		if(k.contains(">>"))
		{
			try {
				reactOnForward();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		if(k.contains("CLEAR"))
		{
			
		}
		if(k.contains("EXIT "))
		{
			
		}
		if(k.contains("startDate"))
		{
			ViewUtilites.makeDateComponent(view.gettStartDate());
		}
		if(k.contains("endDate"))
		{
			ViewUtilites.makeDateComponent(view.gettEndDate());
		}
		
		
	}


}
